section .text
[bits 32]

extern arch_init
extern __code
extern __data
extern __bss
extern __end

global kern_stack
global start
global i386lgdt
global i386lidt
global image_size

MULTIBOOT_PAGE_ALIGN   equ 1<<0
MULTIBOOT_MEMORY_INFO  equ 1<<1
    
MULTIBOOT_HEADER_MAGIC equ 0x1BADB002
MULTIBOOT_HEADER_FLAGS equ MULTIBOOT_PAGE_ALIGN | MULTIBOOT_MEMORY_INFO
CHECKSUM equ -(MULTIBOOT_HEADER_MAGIC + MULTIBOOT_HEADER_FLAGS)
                
; The Multiboot header (in NASM syntax)
align 4
    dd MULTIBOOT_HEADER_MAGIC
    dd MULTIBOOT_HEADER_FLAGS
    dd CHECKSUM

STACKSIZE	equ	4000h	; stack for kernel 16kb size

; startup code
start:
    cli		; disable all irqs
    cld
    
    ; cleaning up .bss section
    xor eax,eax
    mov edi,__bss
    mov ecx,__end
    sub ecx,edi
    rep stosb
    ; new temp stack ptr
    xor ebp,ebp
    mov esp,kern_stack+STACKSIZE
    ; correct to .text section pointer!!!
    mov [image_size],dword (kern_stack+STACKSIZE)-0x100000	; .text section at 1mb mark
    ; cleaning up eflags reg
    push 0
    popf

    push eax    ; pass Multiboot magic
    push ebx    ; pass Multiboot info struct
    call arch_init
    
again:	; halt on exit
    cli
    hlt
    jmp again
    ret

; load gdt register
i386lgdt:
    push ebp
    mov ebp,esp
    sub esp,4

    mov eax,[ebp+8]
    mov [gdtr.addr],eax
    lgdt [gdtr]
    mov ax,16
    mov ds,ax
    mov es,ax
    mov fs,ax
    mov gs,ax
    mov ss,ax
    jmp 8:start_pm

start_pm:
    leave
    ret

; load idt register
i386lidt:
    push ebp
    mov ebp,esp
    sub esp,4

    mov eax,[ebp+8]
    mov [idtr.addr],eax
    lidt [idtr]
    leave
    ret

section .data

align 16
gdtr:
	dw	256*8-1
.addr	dd	0

align 16
idtr:
	dw	256*8-1
.addr	dd	0

image_size:
	dd	0

section .bss

global gdtable
global idtable

gdtable:	; 256 entries * 8 bytes each
    resd	256*2
    
idtable:
    resd	256*2

kern_stack:
    resb	STACKSIZE
    